import { login, getInfo, register, loginWithWeChat } from '@/api/user'
import { getToken, setToken, removeToken, set, remove } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Toast } from 'vant'
import { get as _get } from 'lodash'
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  authTo: '/user/index', // 默认登录后跳转到用户中心
  userId: 0,
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_AUTH_TO: (state, authTo) => {
    set('auth-to', authTo)
    state.authTo = authTo
  },
  SET_USER_ID: (state, id) => {
    state.userId = id
  },
}

const actions = {
  // user login
  async login({ commit }, loginData) {
    try {
      const { code, token, msg, name, avatar, userId } = await login(loginData)
      if (code === 0) {
        commit('SET_TOKEN', token)
        setToken(token)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        set('avatar', avatar)
        set('name', name)
        commit('SET_USER_ID', parseInt(userId))
        set('user_id', parseInt(userId))
      }
      if (msg) {
        Toast.fail(msg)
      } else {
        Toast.fail('登录失败，账号或密码错误')
      }
      return true
    } catch (e) {
      const msg = _get(e, 'response.data.msg', '登录失败，账号或密码错误')
      if (msg) {
        Toast.fail(msg)
      }
      return false
    }
  },
  async loginWithWeChat({ commit }, wxCode) {
    try {
      const { code, data } = await loginWithWeChat(wxCode)
      if (code === 0) {
        // 解析返回的数据
        commit('SET_TOKEN', data.Token)
        setToken(data.Token)
        commit('SET_NAME', data.User.nickName)
        commit('SET_AVATAR', data.User.face)
        set('avatar', data.User.face)
        set('name', data.User.nickName)
        const userId = parseInt(data.User.userId)
        commit('SET_USER_ID', userId)
        set('user_id', userId)
        return true
      } else {
        Toast.fail('微信登录失败，请重试')
        return false
      }
    } catch (e) {
      const msg = _get(e, 'response.data.message')
      if (msg) {
        Toast.fail(msg)
      }
      return false
    }
  },
  async register({ commit }, userInfo) {
    try {
      const { token, code, msg, name, avatar } = await register(userInfo)
      if (code === 0) {
        commit('SET_TOKEN', token)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        set('avatar', avatar)
        set('name', name)
        setToken(token)
        return true
      } else {
        Toast.fail(msg || '注册失败')
        return false
      }
    } catch (e) {
      const msg = _get(e, 'response.data.message')
      if (msg) {
        Toast.fail(msg)
      }
      return false
    }
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { roles, name, avatar, introduction } = data

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resetRouter()
      remove('avatar')
      remove('name')
      remove('user_id')
      commit('SET_AVATAR', '')
      commit('SET_NAME', '')
      commit('SET_USER_ID', 0)
      resolve(true)
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
